package com.cxj.lejia;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.waps.AppConnect;
import com.waps.UpdatePointsNotifier;

public class MainActivity extends Activity implements UpdatePointsNotifier {
    private static Pair[] items = null;
    private static final int LEN = 30;
    private static final String TAG = "LEJIA";

    private ListView listView;
    private Button queryButton;
    private Button clearButton;

    public static int currentPointTotal = 0;// 当前积分
    public static final int requirePoint = 30;// 要求积分
    public static boolean hasEnoughRequrePoint = false;// 是否达到积分

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // 连接服务器. 应用启动时调用(为了统计准确性，此句必须填写).
        AppConnect.getInstance(this);
        AppConnect.getInstance(this).spendPoints(20, this);

        List<Pair> tmpPairs = new ArrayList<Pair>();
        try {
            InputStream is = getResources().openRawResource(R.raw.timu);
            LineNumberReader fr = new LineNumberReader(new InputStreamReader(is));

            Pair pair = null;
            int i = 0;
            for (String line = fr.readLine(); line != null; line = fr.readLine()) {
                i++;
                if (i == 1 || i == 6) {
                    pair = new Pair();
                    pair.title = line;
                    pair.sa = new String[4];
                    tmpPairs.add(pair);
                    i = 1;
                } else {
                    pair.sa[i - 2] = line;
                }
            }
            items = tmpPairs.toArray(new Pair[0]);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        listView = (ListView) findViewById(R.id.list);
        final IconicAdapter adapter = new IconicAdapter();
        listView.setAdapter(adapter);

        clearButton = (Button) findViewById(R.id.clear_button);
        clearButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.happy2).setTitle("确认要清除?")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialoginterface, int i) {
                                for (int pos = 0; pos < LEN; pos++) {
                                    View view = listView.getAdapter().getView(pos, null, null);
                                    ViewHolder holder = (ViewHolder) view.getTag();
                                    if (holder != null) {
                                        holder.radiogroup.clearCheck();
                                    }
                                }
                                //更新所有题目答案
                                MainActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        adapter.notifyDataSetChanged();
                                    }
                                });
                                //回滚到第一题
                                View top = listView.getAdapter().getView(0, null, null);
                                listView.setSelectionFromTop(0, top.getTop());
                            }
                        }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();
            }
        });

        queryButton = (Button) findViewById(R.id.query_button);
        queryButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean ok = true;
                int la = 0, lb = 0, lc = 0, ld = 0;
                int ra = 0, rb = 0, rc = 0, rd = 0;

                for (int pos = 0; pos < LEN; pos++) {
                    View view = listView.getAdapter().getView(pos, null, null);
                    RadioGroup row = (RadioGroup) view.findViewById(R.id.main_radio);
                    int checkedId = row.getCheckedRadioButtonId();
                    Log.d(TAG, "pos is " + checkedId);
                    if (checkedId == -1) {
                        // 提示题目未做完
                        Toast.makeText(getApplicationContext(), "题目" + (pos + 1) + "还没做完!", Toast.LENGTH_SHORT).show();
                        listView.setSelectionFromTop(pos, view.getTop());
                        ok = false;
                        break;
                    }

                    switch (checkedId) {
                    case R.id.radio_button0:
                        if (2 * pos - LEN < 0) {
                            la++;
                        } else {
                            ra++;
                        }
                        break;
                    case R.id.radio_button1:
                        if (2 * pos - LEN < 0) {
                            lb++;
                        } else {
                            rb++;
                        }
                        break;
                    case R.id.radio_button2:
                        if (2 * pos - LEN < 0) {
                            lc++;
                        } else {
                            rc++;
                        }
                        break;
                    case R.id.radio_button3:
                        if (2 * pos - LEN < 0) {
                            ld++;
                        } else {
                            rd++;
                        }
                        break;
                    }
                }

                // 统计并得到最终结果
                if (ok) {
                    int red = la + rd;// 红色：前A+后D的总数
                    int blue = lb + rc;// 蓝色：前B+后C的总数
                    int yellow = lc + rb;// 黄色：前C+后B的总数
                    int green = ld + ra;// 绿色：前D+后A的总数

                    Log.i(TAG, "red:" + red + ",blue:" + blue + ",yellow:" + yellow + ",green:" + green);

                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, DetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("red", red);
                    bundle.putInt("blue", blue);
                    bundle.putInt("yellow", yellow);
                    bundle.putInt("green", green);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        AppConnect.getInstance(MainActivity.this).getPushAd();
                        AppConnect.getInstance(MainActivity.this).getPoints(MainActivity.this);
                        Thread.currentThread().sleep(1850 * 1000);
                    } catch (Exception e) {
                        Log.e("MyError", e.getMessage());
                    }
                }
            }
        }).start();
    }

    private class IconicAdapter extends ArrayAdapter<Pair> {
        IconicAdapter() {
            super(MainActivity.this, R.layout.entry, items);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            if (row == null) {
                LayoutInflater infalter = getLayoutInflater();
                row = infalter.inflate(R.layout.entry, parent, false);
            }
            ViewHolder holder = (ViewHolder) row.getTag();

            if (holder == null) {
                holder = new ViewHolder(row);
                row.setTag(holder);

                RadioGroup.OnCheckedChangeListener l = new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        Log.d(TAG, "change checkedid :" + checkedId);
                        Integer myPosition = (Integer) group.getTag();
                        Pair model = IconicAdapter.this.getItem(myPosition);
                        model.checkid = checkedId;
                    }
                };
                holder.radiogroup.setOnCheckedChangeListener(l);
            }

            TextView label = (TextView) row.findViewById(R.id.text_view);
            label.setText(items[position].title);

            RadioButton rb0 = (RadioButton) row.findViewById(R.id.radio_button0);
            RadioButton rb1 = (RadioButton) row.findViewById(R.id.radio_button1);
            RadioButton rb2 = (RadioButton) row.findViewById(R.id.radio_button2);
            RadioButton rb3 = (RadioButton) row.findViewById(R.id.radio_button3);

            String[] sa = items[position].sa;
            rb0.setText(sa[0]);
            rb1.setText(sa[1]);
            rb2.setText(sa[2]);
            rb3.setText(sa[3]);

            holder.radiogroup.setTag(new Integer(position));
            holder.radiogroup.check(getItem(position).checkid);

            return row;
        }
    }

    private static class Pair {
        public String title;
        public String[] sa;
        public int checkid = -1;

        @Override
        public String toString() {
            return "title:" + title + "," + sa[0] + "," + sa[1] + "," + sa[2] + "," + sa[3];
        }
    }

    private static class ViewHolder {
        RadioGroup radiogroup = null;

        ViewHolder(View base) {
            this.radiogroup = (RadioGroup) base.findViewById(R.id.main_radio);
        }
    }

    /**
     * AppConnect.getPoints()方法的实现，必须实现
     *
     * @param currencyName
     *            虚拟货币名称.
     * @param pointTotal
     *            虚拟货币余额.
     */
    public void getUpdatePoints(String currencyName, int pointTotal) {
        currentPointTotal = pointTotal;
        if (currentPointTotal >= requirePoint) {
            hasEnoughRequrePoint = true;
        }
    }

    /**
     * AppConnect.getPoints() 方法的实现，必须实现
     *
     * @param error
     *            请求失败的错误信息
     */

    public void getUpdatePointsFailed(String error) {
        currentPointTotal = 0;
    }

    @Override
    protected void onDestroy() {
        AppConnect.getInstance(this).finalize();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        AppConnect.getInstance(this).getPoints(this);
        super.onResume();
    }

    public static void showDialog(final Context context) {
        new AlertDialog.Builder(context)
                .setIcon(R.drawable.happy2)
                .setTitle("当前积分：" + MainActivity.currentPointTotal)
                .setMessage(
                        "只要积分满足" + MainActivity.requirePoint + "，就可以消除本提示信息！！ 您当前的积分不足" + MainActivity.requirePoint
                                + "，所以会有此 提示。\n\n【免费获得积分方法】：请点击【确认键】进入推荐下载列表 , 下载并安装软件获得相应积分，消除本提示！！")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                        // 显示推荐安装程序（Offer）.
                        AppConnect.getInstance(context).showOffers(context);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // finish();
                    }
                }).show();
    }
}